import { useContext, useEffect, useState } from 'react';
import { useMediaPredicate } from 'react-media-hook';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import BackButton from 'src/component/BackButton';
import Button from 'src/component/Button';
import Pagination from 'src/component/Pagination';
import RoundSelect from 'src/component/RoundSelect';
import SelectOption from 'src/component/SelectOption';
import SortingSelect from 'src/component/SortingSelect';
import Tabs from 'src/component/Tabs';
import { MediaQuery } from 'src/constant/Media';
import { Action } from 'src/constant/Order';
import { Page } from 'src/constant/Page';
import { ThemeContext } from 'src/context/ThemeContext';
import { usePagination } from 'src/hook/usePagination';
// import { TradingForm } from 'src/model/Form';
// import { OrderAction, UserOrder } from 'src/model/Order';
import { openSnackbar } from 'src/redux/uiSlice';
import { RootState } from 'src/redux/store';
// import { actionOrder, getUserOrders } from 'src/service/orderService';
import { getMyAdGoods, delMyAdGoods } from 'src/service/orderService';
import Card from './component/Card';
import ConfirmationModal from './component/ConfirmationModal';
// import RedirectModal from './component/RedirectModal';
import Table from './component/Table';
import style from './MyTrade.module.scss';

type TradingForm = any
type OrderAction = any
type UserOrder = any

const MyTrade = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const isBiggerThanMedium = useMediaPredicate(MediaQuery.Md);
  const { IcEmpty } = useContext(ThemeContext).image;
  const { limit, offset, setCount, paginationProps } = usePagination();
  const [filterStatus, setFilterStatus] = useState<string>('全部');
  const [filterSorting, setFilterSorting] = useState<string>('default');
  const [open, setOpen] = useState<boolean>(false);
  const [orders, setOrders] = useState<UserOrder[]>([]);
  const [allDatas, setAllDatas] = useState<UserOrder[]>([]);
  const [refresh, setRefresh] = useState<boolean>(false);
  const [orderAction, setOrderAction] = useState<OrderAction>();
  const [isConfirmationModalOpen, setConfirmationModalOpen] = useState<boolean>(false);
  const [isActionConfirmed, setActionConfirmed] = useState<boolean>(false);
  const token = localStorage.getItem("token")
  const { accountInfo } = useSelector((rootState: RootState) => rootState.auth);

  useEffect(() => {
    if (!accountInfo?.FID) return
    getMyAdGoods({
      uMail: accountInfo.FMail,
      FUserID: accountInfo?.FID,
      FState: filterStatus,
      token: token,
    }).then(res => {
      setAllDatas(res.list);
      setCount(res.list.length);
    }).catch(e => {
      dispatch(openSnackbar({ message: e, severity: 'alert' }));
    })

  }, [refresh, limit, filterStatus, filterSorting, accountInfo]);

  useEffect(() => {
    if (allDatas.length < 0) return
    let len = offset + limit
    let data = allDatas.slice(offset, len)
    setOrders(data);
  }, [offset, limit, allDatas])


  useEffect(() => {
    if (orderAction === undefined || !isActionConfirmed) return;
    if (orderAction.action === Action.Edit) {
      const state: TradingForm = {
        base: 'usdt',
        quote: 'cny',
        price: orderAction.userOrder.price,
        amount: orderAction.userOrder.openAmount,
        minTotal: orderAction.userOrder.minTotal,
        maxTotal: orderAction.userOrder.maxTotal,
        bankAccountId: orderAction.userOrder.bankAccount.id,
        orderId: orderAction.userOrder.id,
      };
      //   if (orderAction.userOrder.status === 'open')
      //     actionOrder(Action.Suspend, orderAction.userOrder.id)
      //       .then(() => {
      //         navigate(Page.Trading, { state });
      //       })
      //       .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
      //   else navigate(Page.Trading, { state });
    } else
      //   actionOrder(orderAction.action, orderAction.userOrder.id)
      //     .then(() => setRefresh(!refresh))
      //     .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));

      setOrderAction(undefined);
    setActionConfirmed(false);
  }, [orderAction, isActionConfirmed]);

  const onAction = (id: string, thisAction: Action) => {
    const userOrder = orders?.find((value) => value.FID === id);
    setOrderAction({
      action: thisAction,
      userOrder,
    });
    setConfirmationModalOpen(true);
  };

  const onConfirmationModalClosed = (isConfirm: boolean) => {
    setConfirmationModalOpen(false);
    if (isConfirm) {
      delMyAdGoods({
        FID: orderAction.userOrder.FID,
        token: token
      }).then(res => {
        if (res.success) {
          dispatch(openSnackbar({ message: res.message }))
          setRefresh(!refresh)
        } else {
          dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
        }
      })

    }
    // setActionConfirmed(isConfirm);
  };

  const onSortingFilterChange = (value: string) => {
    paginationProps.setPage(1);
    setFilterSorting(value);
  };

  const onStatusFilterChange = (value: string) => {
    paginationProps.setPage(1);
    setFilterStatus(value);
  };


  return (
    <div>
      <BackButton />
      <div className={style.heading}>
        我的广告
        <div className={style.buttons}>
          <Button appearance="text" onClick={() => navigate(Page.Trade, { replace: true })}>
            所有广告
          </Button>
          <Button appearance="text" onClick={() => navigate(Page.Trading)}>
            发布广告
          </Button>
        </div>
      </div>
      {/* <div className={style.status}>
        <div className={style.statusItem}>
          <div className={style.title}>{t('myTrade.desc.completeRate')}</div>
          99%
        </div>
        <div className={style.statusItem}>
          <div className={style.title}>{t('myTrade.desc.numberOfTransactions')}</div>
          26
        </div>
      </div>
      <div className={style.divider} /> */}
      <div className={style.tabs}>
        <Tabs labels={['USDT']} />
      </div>

      <div className={style.listBlock}>
        <div className={style.filterBlockLeft}>
          <div className={style.statusFilter}>
            <RoundSelect
              label="状态"
              defaultValue="全部"
              onChange={onStatusFilterChange}
            >
              <SelectOption value="全部">
                全部
              </SelectOption>
              <SelectOption value="上架中">上架中</SelectOption>
              <SelectOption value="下架中">
                下架中
              </SelectOption>
            </RoundSelect>
          </div>
          <div>
            <SortingSelect defaultValue="default" onChange={onSortingFilterChange}>
              <SelectOption value="default">时间：新 {'>'} 旧</SelectOption>
              <SelectOption value="status">状态</SelectOption>
              <SelectOption value="-price">
                价格：高 {'>'} 低
              </SelectOption>
              <SelectOption value="price">价格：低 {'>'} 高</SelectOption>
              <SelectOption value="-open_amount">
                数量：大 {'>'} 小
              </SelectOption>
              <SelectOption value="open_amount">
                数量：小 {'>'} 大
              </SelectOption>
            </SortingSelect>
          </div>
        </div>

        {orders?.length === 0 && (
          <div className={style.emptyImg}>
            <img src={IcEmpty} />
          </div>
        )}
        {orders &&
          orders.length > 0 &&
          (isBiggerThanMedium ? (
            <Table data={orders} onAction={onAction} />
          ) : (
            <Card data={orders} onAction={onAction} />
          ))}
      </div>
      <div className={style.pagination}>
        <Pagination {...paginationProps} />
      </div>
      <ConfirmationModal
        isOpen={isConfirmationModalOpen}
        action={orderAction?.action}
        onClose={onConfirmationModalClosed}
      />
    </div>
  );
};

export default MyTrade;
